<template>
  <div class="main">
    <!-- 页面头部 -->
    <div class="page-header">
      <h1 class="page-title">收银台</h1>
      <div class="header-controls"></div>
    </div>

    <!-- 内容区域 -->
    <div class="content-area">
      <!-- 居中搜索栏 -->
      <div class="search-wrapper">
        <el-select
          v-model="selectedPayer"
          value-key="id"
          filterable
          remote
          :remote-method="remoteSearch"
          :loading="searchLoading"
          placeholder="输入姓名或手机号进行搜索"
          style="width: 560px"
          clearable
          @change="handlePayerChange"
        >
          <el-option
            v-for="item in searchOptions"
            :key="item.id"
            :label="formatPayerOption(item)"
            :value="item"
          />
        </el-select>
      </div>

      <!-- tabs 区域 -->
      <el-tabs
        v-model="activeTab"
        class="tabs-area"
        @tab-change="handleTabChange"
      >
        <el-tab-pane label="未缴账单" name="unpaid">
          <div class="table-toolbar">
            <div class="toolbar-left">
              <el-button
                type="primary"
                :disabled="selectedUnpaid.length === 0 || !selectedPayer"
                @click="openPayDialog"
              >
                收款 ({{ selectedUnpaid.length }})
              </el-button>
            </div>
            <div class="toolbar-right">
              <el-button @click="selectedUnpaid = []">清空选择</el-button>
            </div>
          </div>

          <el-table
            v-loading="loadingUnpaid"
            :data="unpaidBills"
            stripe
            border
            style="width: 100%"
            @selection-change="onUnpaidSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="cellName" label="小区名称" width="120" />
            <el-table-column
              prop="payer"
              label="缴费人"
              width="120"
              show-overflow-tooltip
            />
            <el-table-column
              prop="payerType"
              label="缴费人类型"
              width="100"
              align="center"
            >
              <template #default="{ row }">
                <el-tag :type="getPayerTypeTag(row.payerType)">{{
                  getPayerTypeText(row.payerType)
                }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column
              prop="phone"
              label="联系电话"
              width="120"
              show-overflow-tooltip
            />
            <el-table-column
              prop="email"
              label="邮箱"
              width="160"
              show-overflow-tooltip
            />
            <el-table-column
              prop="chargestandardName"
              label="收费标准"
              width="120"
              align="center"
            />
            <el-table-column prop="price" label="单价" width="80">
              <template #default="{ row }">¥{{ row.price }}</template>
            </el-table-column>
            <el-table-column
              prop="receivableAmount"
              label="应收金额"
              width="100"
            >
              <template #default="{ row }"
                >¥{{ row.receivableAmount }}</template
              >
            </el-table-column>
            <el-table-column prop="totalAmount" label="总金额" width="100">
              <template #default="{ row }">¥{{ row.totalAmount }}</template>
            </el-table-column>
            <el-table-column
              prop="notification"
              label="通知状态"
              width="100"
              align="center"
            >
              <template #default="{ row }">
                <el-tag
                  :type="row.notification === 1 ? 'success' : 'warning'"
                  >{{ row.notification === 1 ? "已通知" : "未通知" }}</el-tag
                >
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" show-overflow-tooltip />
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="历史缴费" name="paid">
          <el-table
            v-loading="loadingPaid"
            :data="paidBills"
            stripe
            border
            style="width: 100%"
          >
            <el-table-column prop="cellName" label="小区名称" width="120" />
            <el-table-column
              prop="payer"
              label="缴费人"
              width="120"
              show-overflow-tooltip
            />
            <el-table-column
              prop="payerType"
              label="缴费人类型"
              width="100"
              align="center"
            >
              <template #default="{ row }">
                <el-tag :type="getPayerTypeTag(row.payerType)">{{
                  getPayerTypeText(row.payerType)
                }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column
              prop="phone"
              label="联系电话"
              width="120"
              show-overflow-tooltip
            />
            <el-table-column
              prop="email"
              label="邮箱"
              width="160"
              show-overflow-tooltip
            />
            <el-table-column
              prop="chargestandardName"
              label="收费标准"
              width="120"
              align="center"
            />
            <el-table-column prop="price" label="单价" width="80">
              <template #default="{ row }">¥{{ row.price }}</template>
            </el-table-column>
            <el-table-column
              prop="receivableAmount"
              label="应收金额"
              width="100"
            >
              <template #default="{ row }"
                >¥{{ row.receivableAmount }}</template
              >
            </el-table-column>
            <el-table-column prop="totalAmount" label="总金额" width="100">
              <template #default="{ row }">¥{{ row.totalAmount }}</template>
            </el-table-column>
            <el-table-column
              prop="paymentype"
              label="缴费类型"
              width="100"
              align="center"
            >
              <template #default="{ row }">
                <el-tag :type="row.paymentype === 1 ? 'success' : 'info'">
                  {{ row.paymentype === 1 ? "预存款" : "其他" }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" show-overflow-tooltip />
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="预存款" name="predeposit">
          <div class="pre-card">
            <div class="pre-row">
              <div>
                <div>姓名：{{ preInfo?.name || "-" }}</div>
                <div>电话：{{ preInfo?.phone || "-" }}</div>
                <div>邮箱：{{ preInfo?.email || "-" }}</div>
              </div>
              <div class="pre-amount">
                当前余额：<span class="money"
                  >¥{{ preInfo?.amount ?? "-" }}</span
                >
              </div>
            </div>

            <el-divider />

            <div v-if="!hasPreInfo" class="pre-form">
              <el-form
                :model="preForm"
                label-width="100px"
                style="max-width: 480px"
              >
                <el-form-item label="初始金额">
                  <el-input
                    v-model.number="preForm.amount"
                    placeholder="请输入金额"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button
                    type="primary"
                    :disabled="!selectedPayer"
                    @click="handleAddPredeposit"
                    >新增预存款信息</el-button
                  >
                </el-form-item>
              </el-form>
              <div class="tip">未找到该缴费人的预存款信息，请先新增。</div>
            </div>

            <div v-else class="pre-form">
              <el-form
                :model="preForm"
                label-width="100px"
                style="max-width: 480px"
              >
                <el-form-item label="充值金额">
                  <el-input
                    v-model.number="preForm.amount"
                    placeholder="请输入金额"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button
                    type="primary"
                    :disabled="!selectedPayer"
                    @click="handleRecharge"
                    >充值</el-button
                  >
                  <el-button @click="loadPredeposit">刷新</el-button>
                </el-form-item>
              </el-form>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
      <!-- 收款弹窗 -->
      <el-dialog v-model="payDialogVisible" title="收款" width="520px">
        <div class="pay-summary">
          <div>共选择：{{ selectedUnpaid.length }} 条</div>
          <div>
            支付总金额：<span class="pay-money"
              >¥{{ payTotalAmount.toFixed(2) }}</span
            >
          </div>
        </div>

        <el-form label-width="100px">
          <el-form-item label="支付方式">
            <el-radio-group
              v-model="payForm.payType"
              @change="handlePayTypeChange"
            >
              <el-radio :label="1">预存款</el-radio>
              <el-radio :label="2">其他</el-radio>
            </el-radio-group>
          </el-form-item>

          <template v-if="payForm.payType === 1">
            <el-form-item label="当前预存">
              <div>
                <span class="pay-balance">¥{{ preInfo?.amount ?? 0 }}</span>
                <el-button
                  link
                  type="primary"
                  style="margin-left: 8px"
                  @click="openRechargeDialog"
                  >预存充值</el-button
                >
              </div>
            </el-form-item>
            <el-alert
              v-if="preInfo && preInfo.amount < payTotalAmount"
              title="预存金额不足，请先充值"
              type="warning"
              :closable="false"
              show-icon
            />
          </template>
        </el-form>

        <template #footer>
          <el-button @click="payDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            :disabled="isPayDisabled"
            @click="handleConfirmPay"
          >
            支付
          </el-button>
        </template>
      </el-dialog>

      <!-- 预存充值弹窗 -->
      <el-dialog v-model="rechargeDialogVisible" title="预存充值" width="420px">
        <el-form :model="rechargeForm" label-width="100px">
          <el-form-item label="充值金额">
            <el-input
              v-model.number="rechargeForm.amount"
              placeholder="请输入金额"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="rechargeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirmRecharge"
            >充值</el-button
          >
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
import { ElMessage } from "element-plus";
import {
  searchPayers,
  queryPayerUnpaidBills,
  queryPayerPaidBills
} from "@/api/checkstand";
import type { Payer, PayerBillItem } from "@/api/checkstand";
import {
  queryPredeposit,
  addPredeposit,
  rechargePredeposit
} from "@/api/predeposit";
import type { PredepositInfo } from "@/api/predeposit";
import { billPay } from "@/api/checkstand";

defineOptions({ name: "Checkstand" });

// 搜索相关
const searchLoading = ref(false);
const searchOptions = ref<Payer[]>([]);
const selectedPayer = ref<Payer | null>(null);

// tabs
const activeTab = ref<"unpaid" | "paid" | "predeposit">("unpaid");

// 列表数据
const loadingUnpaid = ref(false);
const loadingPaid = ref(false);
const unpaidBills = ref<PayerBillItem[]>([]);
const paidBills = ref<PayerBillItem[]>([]);
const selectedUnpaid = ref<PayerBillItem[]>([]);

// 预存款
const preInfo = ref<PredepositInfo | null>(null);
const hasPreInfo = ref(false);
const preForm = ref<{ amount: number }>({ amount: 0 });

const formatPayerOption = (p: Payer) =>
  `${getPayerTypeText(p.payerType)} - ${p.name} - ${p.phone}`;

// 缴费人类型展示
const getPayerTypeText = (type: number) => {
  const map: Record<number, string> = { 1: "业主", 2: "租房人员", 3: "客户" };
  return map[type] || "未知";
};

const onUnpaidSelectionChange = (selection: PayerBillItem[]) => {
  selectedUnpaid.value = selection;
};

const getPayerTypeTag = (
  type: number
): "success" | "warning" | "info" | "primary" | "danger" => {
  const map: Record<
    number,
    "success" | "warning" | "info" | "primary" | "danger"
  > = {
    1: "success",
    2: "warning",
    3: "info"
  };
  return map[type] || "info";
};

const remoteSearch = async (query: string) => {
  if (!query) {
    searchOptions.value = [];
    return;
  }
  searchLoading.value = true;
  try {
    const res = await searchPayers({ page: 0, limit: 0, name: query });
    if (res.code === 0) {
      searchOptions.value = res.data || [];
    } else {
      ElMessage.error(res.message || "搜索失败");
    }
  } catch (e) {
    ElMessage.error("搜索失败");
    // eslint-disable-next-line no-console
    console.error(e);
  } finally {
    searchLoading.value = false;
  }
};

const handlePayerChange = async (payer: Payer | null) => {
  if (!payer) {
    unpaidBills.value = [];
    paidBills.value = [];
    preInfo.value = null;
    hasPreInfo.value = false;
    return;
  }
  await loadUnpaidBills(payer);
  if (activeTab.value === "paid") {
    await loadPaidBills(payer);
  }
  if (activeTab.value === "predeposit") {
    await loadPredeposit();
  }
};

const loadUnpaidBills = async (payer: Payer) => {
  loadingUnpaid.value = true;
  try {
    const res = await queryPayerUnpaidBills({
      payerId: payer.id,
      payerType: payer.payerType
    });
    if (res.code === 0) {
      unpaidBills.value = res.data || [];
    } else {
      ElMessage.error(res.message || "获取未缴账单失败");
    }
  } catch (e) {
    ElMessage.error("获取未缴账单失败");
    // eslint-disable-next-line no-console
    console.error(e);
  } finally {
    loadingUnpaid.value = false;
  }
};

const loadPaidBills = async (payer: Payer) => {
  loadingPaid.value = true;
  try {
    const res = await queryPayerPaidBills({
      payerId: payer.id,
      payerType: payer.payerType
    });
    if (res.code === 0) {
      paidBills.value = res.data || [];
    } else {
      ElMessage.error(res.message || "获取历史缴费失败");
    }
  } catch (e) {
    ElMessage.error("获取历史缴费失败");
    // eslint-disable-next-line no-console
    console.error(e);
  } finally {
    loadingPaid.value = false;
  }
};

const handleTabChange = async (name: string | number) => {
  if (name === "paid" && selectedPayer.value) {
    await loadPaidBills(selectedPayer.value);
  }
  if (name === "predeposit" && selectedPayer.value) {
    await loadPredeposit();
  }
};

const loadPredeposit = async () => {
  if (!selectedPayer.value) return;
  try {
    const res = await queryPredeposit({
      payerId: selectedPayer.value.id,
      payerType: selectedPayer.value.payerType
    });
    if (res.code === 0) {
      preInfo.value = res.data;
      hasPreInfo.value = !!res.data && res.data.id !== null;
    } else {
      ElMessage.error(res.message || "获取预存款信息失败");
    }
  } catch (e) {
    ElMessage.error("获取预存款信息失败");
    // eslint-disable-next-line no-console
    console.error(e);
  }
};

const handleAddPredeposit = async () => {
  if (!selectedPayer.value) return;
  try {
    const res = await addPredeposit({
      payerId: selectedPayer.value.id,
      payerType: selectedPayer.value.payerType,
      amount: preForm.value.amount
    });
    if (res.code === 0) {
      ElMessage.success("新增成功");
      await loadPredeposit();
    } else {
      ElMessage.error(res.message || "新增失败");
    }
  } catch (e) {
    ElMessage.error("新增失败");
    // eslint-disable-next-line no-console
    console.error(e);
  }
};

const handleRecharge = async () => {
  if (!selectedPayer.value) return;
  try {
    const res = await rechargePredeposit({
      payerId: selectedPayer.value.id,
      payerType: selectedPayer.value.payerType,
      amount: preForm.value.amount
    });
    if (res.code === 0) {
      ElMessage.success("充值成功");
      await loadPredeposit();
    } else {
      ElMessage.error(res.message || "充值失败");
    }
  } catch (e) {
    ElMessage.error("充值失败");
    // eslint-disable-next-line no-console
    console.error(e);
  }
};

// ------- 支付相关 -------
const payDialogVisible = ref(false);
const rechargeDialogVisible = ref(false);
const payForm = ref<{ payType: 1 | 2 }>({ payType: 1 });
const payTotalAmount = computed(() =>
  selectedUnpaid.value.reduce((sum, cur) => sum + (cur.totalAmount || 0), 0)
);

const isPayDisabled = computed(() => {
  if (payForm.value.payType === 2) return selectedUnpaid.value.length === 0;
  const balance = preInfo.value?.amount ?? 0;
  return selectedUnpaid.value.length === 0 || balance < payTotalAmount.value;
});

const openPayDialog = async () => {
  if (selectedPayer.value) {
    await loadPredeposit();
  }
  payForm.value.payType = 1;
  payDialogVisible.value = true;
};

const handlePayTypeChange = async () => {
  if (payForm.value.payType === 1 && selectedPayer.value) {
    await loadPredeposit();
    // 检查预存金额是否足够
    const balance = preInfo.value?.amount ?? 0;
    if (balance < payTotalAmount.value) {
      // 预存金额不足，关闭支付弹窗，跳转到预存页面
      payDialogVisible.value = false;
      activeTab.value = "predeposit";
      ElMessage.warning("预存金额不足，请先充值");
    }
  }
};

const rechargeForm = ref<{ amount: number }>({ amount: 0 });

const openRechargeDialog = () => {
  rechargeForm.value.amount = 0;
  rechargeDialogVisible.value = true;
};

const handleConfirmRecharge = async () => {
  if (!selectedPayer.value) return;
  const amt = Number(rechargeForm.value.amount) || 0;
  if (amt <= 0) {
    ElMessage.warning("请输入正确的充值金额");
    return;
  }
  const res = await rechargePredeposit({
    payerId: selectedPayer.value.id,
    payerType: selectedPayer.value.payerType,
    amount: amt
  });
  if (res.code === 0) {
    ElMessage.success("充值成功");
    rechargeDialogVisible.value = false;
    await loadPredeposit();
  } else {
    ElMessage.error(res.message || "充值失败");
  }
};

const handleConfirmPay = async () => {
  if (!selectedPayer.value || selectedUnpaid.value.length === 0) return;
  const ids = selectedUnpaid.value
    .map(i => i.id)
    .filter(id => typeof id === "number") as number[];
  const body = {
    ids,
    payType: payForm.value.payType,
    amount: Number(payTotalAmount.value.toFixed(2))
  } as const;
  const res = await billPay(body);
  if (res.code === 0) {
    ElMessage.success("支付成功");
    payDialogVisible.value = false;
    selectedUnpaid.value = [];
    await loadUnpaidBills(selectedPayer.value);
    if (activeTab.value === "paid") await loadPaidBills(selectedPayer.value);
    await loadPredeposit();
  } else {
    ElMessage.error(res.message || "支付失败");
  }
};
</script>

<style scoped>
.main {
  min-height: 100vh;
  padding: 20px;
  background-color: #f5f7fa;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px;
  margin-bottom: 30px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgb(0 0 0 / 10%);
}

.page-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.header-controls {
  display: flex;
  gap: 10px;
  align-items: center;
}

.content-area {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgb(0 0 0 / 10%);
  min-height: 400px;
  padding: 20px; /* 增加左右内边距让表格不贴边 */
}

.search-wrapper {
  display: flex;
  justify-content: center;
  padding: 40px 0 20px;
}

.tabs-area {
  margin-top: 10px;
}

.pre-card {
  padding: 10px 0;
}

.pre-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pre-amount .money {
  color: #67c23a;
  font-size: 18px;
  font-weight: 600;
}

.pre-form {
  margin-top: 10px;
}

.tip {
  color: #909399;
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.pay-summary {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6px 0 16px;
}
.pay-money {
  color: #f56c6c;
  font-weight: 600;
}
.pay-balance {
  color: #67c23a;
  font-weight: 600;
}
</style>
